var Client = function(vm,u){
	var self=this;
	var viewModel=vm;
	var url=u;
	var monitors=new Array(4);
	var serverInterval=null;
	var isConnected = false;
	var session={
		connect : function() {
			if(!this._ws){
				var location = url;
				//this.viewModel=vm;
				this._ws = new WebSocket(location);
				this._ws.onopen = this._onopen;
				this._ws.onmessage = this._onmessage;
				this._ws.onclose = this._onclose;
				
			}
		},
		reconnect : function() {			
			if(this._ws.readyState!=1){//如果已连接，就不重连
				var that=this;//interval里面的this变为了window  -0-
				var location = url;
				serverInterval=setInterval(function(){
					console.log("trying reconnect...");
					that._ws = new WebSocket(location);
					
					/**下面的不要写在重连里面，否则会导致断开不断执行**/
					that._ws.onopen = that._onopen;
					/*that._ws.onopen = that._onopen;
					that._ws.onmessage = that._onmessage;
					that._ws.onclose = that._onclose;	*/			

				},60000);					
			}				
		},
		send : function(message) {//如果session被占用，发送消息需要延时
			if (this._ws&&this._ws.readyState === 1) {  
				if (message != null && message.length > 0)
					this._ws.send(message);
		    } else {  
		        var that = this;  
		        setTimeout(function () {  
		            that.send(message);  
		        }, 100);  
		    }
			
			
//			if (this._ws&&this._ws.readyState==1)
//				if (message != null && message.length > 0)
//					this._ws.send(message);
		},
	
		disconnect : function() {
			if (this._ws != null) {
				this._ws.close();
				this._ws = null;
				monitors.splice(0, 4);
			}
		},
		addMonitor:function(opcode,freeIndex){//增加到监控点op code的列表
			monitors[freeIndex]=opcode;
			//告诉后台当店监控点增加
			if (this._ws != null) {
				viewModel.client.session.send(JSON.stringify({msgType:_CONST.WS_TYPE_OPADD,opcode:opcode,content:""}));
			}			
		},
		removeMonitor:function(opcode,index){//从监控点op code的列表删除
			//清除消息
//			var cindex=session.getConsoleIndex(opcode);			
			$("#message"+(index+1)).html("");
			$("#weight"+(index+1)).val("");
			monitors[index]=null;
			
			//告诉后台监控点减少
			if (this._ws != null) {
				viewModel.client.session.send(JSON.stringify({msgType:_CONST.WS_TYPE_OPDELETE,opcode:opcode,content:""}));
			}
		},
		getConsoleIndex : function(opcode){//找到这个opcode对应在第几个控制台
			var cindex;
			for(cindex=3;cindex>=0;cindex--){
				if(monitors[cindex]==opcode){
					break;
				}
			}
			return cindex;
		},		
		_onopen : function() {
			console.log("Open connection.");
			
			//如果isConnected = true，说明是异常断开,重新把断了的作业点告知后台
			if(isConnected){
				viewModel.client.session._ws.onmessage = viewModel.client.session._onmessage;
				viewModel.client.session._ws.onclose = viewModel.client.session._onclose;
				for(var m in monitors){
					viewModel.client.session.send(JSON.stringify({msgType:_CONST.WS_TYPE_OPADD,opcode:monitors[m],content:""}));
				}
			}
			isConnected = true;
			heartCheck.start();
			clearInterval(serverInterval);//重连机制
		},
		_onmessage : function(m) {
			if (m.data) {
				//收到消息，更新页面显示
				var d = JSON.parse(m.data);
				//是否是心跳包消息
				if(d.msgType==_CONST.WS_TYPE_HEARTCHECK){
					console.log(_CONST.WS_TYPE_HEARTCHECK);
					return;
				}
				
				//判断更新哪个Data
				var opcode= d.opcode;				
				//找到这个opcode对应在第几个控制台
				var cindex=session.getConsoleIndex(opcode);		
				if(cindex==-1)return;
				if(d.msgType==_CONST.WS_TYPE_CARINFO){//车辆基本信息
					viewModel['monitorData'+(cindex+1)].setSimpleData(JSON.parse(d.content));
				}else if(d.msgType==_CONST.WS_TYPE_WEIGHT){//称重
					$("#weight"+(cindex+1)).val(d.content);
				}else if(d.msgType==_CONST.WS_TYPE_CARMSG){//实时消息
//					console.log(d.content);
					$("#message"+(cindex+1)).append(d.content+"<br/>");
					var div=$("#message"+(cindex+1))[0];
					div.scrollTop = div.scrollHeight;//保证显示低端
					
				}else if(d.msgType==_CONST.WS_TYPE_CARSTATUS){//车辆动画变化指令
					if(d.content == "99"){//改为下一个状态
						var curImg = $("#mimg"+(cindex+1)).attr("src");
						var curState = curImg.charAt(curImg.length-5);
						var nextState = (curState+1)%4;
						$("#mimg"+(cindex+1)).attr("src",ctx+"/static/status"+nextState+".png");
					}else{
						$("#mimg"+(cindex+1)).attr("src",ctx+"/static/status"+d.content+".png");
					}					
				}else if(d.msgType==_CONST.WS_TYPE_EXCEPTIONS){
					//异常消息
					viewModel["exceptionsLight"+(cindex+1)](d.content==""?"一切正常":d.content);
					//修改灯的颜色,如果没有异常消息，那就是正常
					if(d.content==""){
						$("#monitor-light"+(cindex+1)).removeClass("u-light-red");
						$("#monitor-light"+(cindex+1)).addClass("u-light-green");
					}else{
						$("#monitor-light"+(cindex+1)).removeClass("u-light-green");
						$("#monitor-light"+(cindex+1)).addClass("u-light-red");
					}
				}
			}
			heartCheck.reset();
			heartCheck.start();
			
		},	
		_onclose : function() {
			console.log("close");
			viewModel.client.session.reconnect();			
		}	
	};
	/**
	 * 心跳包，用户检测因为服务端网络异常或者其他原因造成的断开连接，原理是在60秒没有收到消息时向客户端发送一个消息，
	 * 如果发送成功，就说明没有断开，否则连接已经断开。当检测到以后，会执行ws的onclose方法。
	 * 注：如果是因为客户端网络异常造成的断开，则会自动触发onclose，不需要检测。
	 */
	var heartCheck = {
	    timeout: 60000,//60s
	    timeoutObj: null,
	    reset: function(){//收到消息就重置计时器
	    	clearTimeout(this.timeoutObj);
	    },
	    start: function(){//直到60s没收到消息才向后台发送心跳包，如果超时，会调用onClose方法。
	        this.timeoutObj = setTimeout(function(){
	        	viewModel.client.session.send(JSON.stringify({msgType:_CONST.WS_TYPE_HEARTCHECK,opcode:"",content:""}));
	        }, this.timeout)
	    }
	}

	return{
		session:session
	}
};
